/**
 * @author Steve Gao<gaofu@parllay.com>
 */
const mobileDetect = require('mobile-detect');
const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class CommunityIndexHandler extends BaseHandler {

    get pattern() {
        return '/community/:wall_id';
    }

    doGET(request, response) {
        var me = this;
        var session = request.session;
        var params = request.params;
        var user_id = request.session.user.id;
        //Add some bad logic here to handle 电视家浏览器's bloody shit logic.
        if(params.wall_id) {
            params.wall_id = request.params.wall_id = params.wall_id.replace(/\.com/g, '');
        }
        if(!request.session.walls[params.wall_id]) {
            request.session.walls[params.wall_id] = {};
        }
        this.Controller.getWallById(request.params.wall_id,  (wall) => {
            if(wall.app_id) {
                request.session.walls[params.wall_id].app_id = wall.app_id;
                //TODO: 考虑一下第三方平台网页授权https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=c3c903dca596f634e5532089438139ab98dacc68&lang=zh_CN
                if(session.is_wechat && (!session.walls[params.wall_id].wall_user_id || (!request.query.tried && session.walls[params.wall_id].is_anonymous))) {
                    me.Controller.getWeChatUserOAuthUrl(wall.app_id, request, (url) => {
                        if(url === 'anonymous') {
                            me.Controller.ensureAnonymousUser(request, session.walls[params.wall_id].wall_user_id, (userId) => {
                                response.redirect('/wall/' + params.wall_id + '/authorize?anonymous_user_id=' + userId);
                            });
                        } else {
                            response.redirect(url);
                        }
                    });
                } else if(!session.is_wechat && !request.session.walls[params.wall_id].wall_user_id) {
                    me.Controller.ensureAnonymousUser(request, session.walls[params.wall_id].wall_user_id, (userId) => {
                        response.redirect('/wall/' + params.wall_id + '/authorize?anonymous_user_id=' + userId);
                    });
                } else {
                    var isAdmin = (wall.administrators.indexOf(session.walls[params.wall_id].wall_user_id) >= 0);
                    var isAuthor = (wall.author.indexOf(session.walls[params.wall_id].wall_user_id )>= 0);
                    me.Controller.getWeChatJssdkConfig(wall.app_id, request, (config) => {
                        var detector = new mobileDetect(request.headers['user-agent']);
                        me.Controller.getPlanInfo(wall.user_id, (result) => {
                            result.data = result.data || {};
                            if(result) {
                                response.render('wall/home', {
                                    wall: wall,
                                    wall_id: params.wall_id,
                                    config: config,
                                    user_authority: wall.user_authority || '',
                                    is_admin: isAdmin,
                                    is_author: isAuthor,
                                    is_wechat: session.is_wechat,
                                    is_realtime: wall.realtime.is_active,
                                    realtime_stop_timestamp: wall.realtime.stop_timestamp,
                                    is_phone: (!!detector.phone() && !!detector.mobile()) || session.is_wechat,
                                    is_anonymous: (session.walls[params.wall_id].is_anonymous === undefined) ? false : session.walls[params.wall_id].is_anonymous,
                                    plan: result.data
                                });
                            } else {
                                //TODO: Implement no plan or plan expired logic here
                                response.end('No plan');
                            }
                            
                        });
                    });
                }
            } else {
                response.redirect('/login');
            }
        });
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = CommunityIndexHandler;